"""主窗口实现"""

import asyncio
from pathlib import Path
from typing import Optional

from PyQt6.QtWidgets import (
    QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QTabWidget,
    QLabel, QPushButton, QProgressBar, QTreeWidget, QTreeWidgetItem,
    QSplitter, QStatusBar, QMenuBar, QMenu, QMessageBox, QFileDialog
)
from PyQt6.QtCore import Qt, QTimer, pyqtSignal
from PyQt6.QtGui import QAction, QIcon

from ..config.system import get_config
from ..monitor.hardware_monitor import HardwareMonitor, HardwareComponent
from ..scheduler.task import TranscodeTask, TaskStatus
from ..scheduler.queue import TaskQueue


class VideoTranscoderApp(QMainWindow):
    """视频转码系统主窗口"""
    
    # 信号定义
    hardware_data_updated = pyqtSignal(dict)
    task_progress_updated = pyqtSignal(dict)
    
    def __init__(self):
        super().__init__()
        self.config = get_config()
        self.hardware_monitor = HardwareMonitor()
        self.task_queue = TaskQueue()
        self.update_timer = QTimer()
        
        self.init_ui()
        self.init_signals()
        # 监控将在主程序的事件循环中启动
    
    def init_ui(self):
        """初始化用户界面"""
        self.setWindowTitle("视频转码系统")
        self.setGeometry(100, 100, 1400, 900)
        
        # 创建中心部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 主布局
        main_layout = QHBoxLayout(central_widget)
        
        # 左侧面板 - 硬件监控树
        left_panel = self.create_left_panel()
        
        # 右侧面板 - 主内容区域
        right_panel = self.create_right_panel()
        
        # 分割器
        splitter = QSplitter(Qt.Orientation.Horizontal)
        splitter.addWidget(left_panel)
        splitter.addWidget(right_panel)
        splitter.setSizes([300, 1100])
        
        main_layout.addWidget(splitter)
        
        # 状态栏
        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)
        self.status_bar.showMessage("系统就绪")
        
        # 菜单栏
        self.create_menu_bar()
    
    def create_left_panel(self) -> QWidget:
        """创建左侧面板"""
        panel = QWidget()
        layout = QVBoxLayout(panel)
        
        # 硬件监控标题
        title_label = QLabel("📊 硬件监控")
        title_label.setStyleSheet("font-size: 16px; font-weight: bold; margin: 10px;")
        layout.addWidget(title_label)
        
        # 硬件树状视图
        self.hardware_tree = QTreeWidget()
        self.hardware_tree.setHeaderLabels(["硬件组件", "状态", "数值"])
        self.hardware_tree.setColumnWidth(0, 150)
        self.hardware_tree.setColumnWidth(1, 80)
        self.hardware_tree.setColumnWidth(2, 80)
        layout.addWidget(self.hardware_tree)
        
        # 刷新按钮
        refresh_btn = QPushButton("刷新")
        refresh_btn.clicked.connect(self.refresh_hardware_data)
        layout.addWidget(refresh_btn)
        
        return panel
    
    def create_right_panel(self) -> QWidget:
        """创建右侧面板"""
        panel = QWidget()
        layout = QVBoxLayout(panel)
        
        # 标签页控件
        self.tab_widget = QTabWidget()
        
        # 转码任务标签页
        self.tasks_tab = self.create_tasks_tab()
        self.tab_widget.addTab(self.tasks_tab, "📹 转码任务")
        
        # 性能监控标签页
        self.monitor_tab = self.create_monitor_tab()
        self.tab_widget.addTab(self.monitor_tab, "📈 性能监控")
        
        # 系统设置标签页
        self.settings_tab = self.create_settings_tab()
        self.tab_widget.addTab(self.settings_tab, "⚙️ 系统设置")
        
        layout.addWidget(self.tab_widget)
        
        return panel
    
    def create_tasks_tab(self) -> QWidget:
        """创建转码任务标签页"""
        tab = QWidget()
        layout = QVBoxLayout(tab)
        
        # 任务控制按钮
        control_layout = QHBoxLayout()
        
        add_task_btn = QPushButton("添加任务")
        add_task_btn.clicked.connect(self.add_transcode_task)
        control_layout.addWidget(add_task_btn)
        
        start_all_btn = QPushButton("开始全部")
        start_all_btn.clicked.connect(self.start_all_tasks)
        control_layout.addWidget(start_all_btn)
        
        pause_all_btn = QPushButton("暂停全部")
        pause_all_btn.clicked.connect(self.pause_all_tasks)
        control_layout.addWidget(pause_all_btn)
        
        layout.addLayout(control_layout)
        
        # 总体进度
        overall_layout = QHBoxLayout()
        overall_layout.addWidget(QLabel("总体进度:"))
        self.overall_progress = QProgressBar()
        overall_layout.addWidget(self.overall_progress)
        layout.addLayout(overall_layout)
        
        # 任务列表
        self.tasks_list = QTreeWidget()
        self.tasks_list.setHeaderLabels(["任务", "状态", "进度", "FPS", "剩余时间"])
        layout.addWidget(self.tasks_list)
        
        return tab
    
    def create_monitor_tab(self) -> QWidget:
        """创建性能监控标签页"""
        tab = QWidget()
        layout = QVBoxLayout(tab)
        
        # CPU监控
        cpu_layout = QVBoxLayout()
        cpu_layout.addWidget(QLabel("💻 CPU监控"))
        self.cpu_usage_bar = QProgressBar()
        cpu_layout.addWidget(self.cpu_usage_bar)
        layout.addLayout(cpu_layout)
        
        # GPU监控
        gpu_layout = QVBoxLayout()
        gpu_layout.addWidget(QLabel("🎮 GPU监控"))
        self.gpu_usage_bar = QProgressBar()
        gpu_layout.addWidget(self.gpu_usage_bar)
        layout.addLayout(gpu_layout)
        
        # 内存监控
        memory_layout = QVBoxLayout()
        memory_layout.addWidget(QLabel("💾 内存监控"))
        self.memory_usage_bar = QProgressBar()
        memory_layout.addWidget(self.memory_usage_bar)
        layout.addLayout(memory_layout)
        
        return tab
    
    def create_settings_tab(self) -> QWidget:
        """创建设置标签页"""
        tab = QWidget()
        layout = QVBoxLayout(tab)
        
        layout.addWidget(QLabel("系统设置界面待实现..."))
        
        return tab
    
    def create_menu_bar(self):
        """创建菜单栏"""
        menu_bar = self.menuBar()
        
        # 文件菜单
        file_menu = menu_bar.addMenu("文件(&F)")
        
        new_task_action = QAction("新建任务", self)
        new_task_action.setShortcut("Ctrl+N")
        new_task_action.triggered.connect(self.add_transcode_task)
        file_menu.addAction(new_task_action)
        
        file_menu.addSeparator()
        
        exit_action = QAction("退出", self)
        exit_action.setShortcut("Ctrl+Q")
        exit_action.triggered.connect(self.close)
        file_menu.addAction(exit_action)
        
        # 视图菜单
        view_menu = menu_bar.addMenu("视图(&V)")
        
        monitor_action = QAction("性能监控", self)
        monitor_action.setShortcut("Ctrl+R")
        monitor_action.triggered.connect(lambda: self.tab_widget.setCurrentIndex(1))
        view_menu.addAction(monitor_action)
        
        tasks_action = QAction("转码任务", self)
        tasks_action.setShortcut("Ctrl+T")
        tasks_action.triggered.connect(lambda: self.tab_widget.setCurrentIndex(0))
        view_menu.addAction(tasks_action)
        
        # 帮助菜单
        help_menu = menu_bar.addMenu("帮助(&H)")
        
        about_action = QAction("关于", self)
        about_action.triggered.connect(self.show_about_dialog)
        help_menu.addAction(about_action)
    
    def init_signals(self):
        """初始化信号连接"""
        self.hardware_data_updated.connect(self.update_hardware_display)
        self.task_progress_updated.connect(self.update_task_display)
        
        # 设置定时器
        self.update_timer.timeout.connect(self.update_display)
        self.update_timer.start(1000)  # 1秒更新一次
    
    async def start_monitoring(self):
        """开始硬件监控"""
        if await self.hardware_monitor.initialize():
            asyncio.create_task(self.hardware_monitor.start_monitoring())
    
    def refresh_hardware_data(self):
        """刷新硬件数据"""
        hardware_data = self.hardware_monitor.get_sensor_data()
        self.hardware_data_updated.emit(hardware_data)
    
    def update_hardware_display(self, hardware_data: dict):
        """更新硬件显示"""
        self.hardware_tree.clear()
        
        for component_id, component in hardware_data.items():
            component_item = QTreeWidgetItem(self.hardware_tree)
            component_item.setText(0, component.name)
            component_item.setText(1, component.component_type)
            
            for sensor in component.sensors:
                sensor_item = QTreeWidgetItem(component_item)
                sensor_item.setText(0, sensor.name)
                sensor_item.setText(1, sensor.unit)
                sensor_item.setText(2, f"{sensor.value:.1f}")
    
    def update_task_display(self, task_data: dict):
        """更新任务显示"""
        # 更新总体进度
        self.overall_progress.setValue(int(task_data.get("overall_progress", 0)))
        
        # 更新任务列表
        self.tasks_list.clear()
        
        # 这里需要实际的任务数据来更新界面
        # 暂时显示占位信息
        placeholder_item = QTreeWidgetItem(self.tasks_list)
        placeholder_item.setText(0, "暂无任务")
        placeholder_item.setText(1, "-")
        placeholder_item.setText(2, "-")
        placeholder_item.setText(3, "-")
        placeholder_item.setText(4, "-")
    
    def update_display(self):
        """定时更新显示"""
        # 更新硬件数据
        hardware_data = self.hardware_monitor.get_sensor_data()
        self.update_hardware_display(hardware_data)
        
        # 更新性能监控
        self.update_performance_monitors(hardware_data)
        
        # 更新任务数据
        task_stats = self.task_queue.get_progress_summary()
        self.update_task_display(task_stats)
    
    def update_performance_monitors(self, hardware_data: dict):
        """更新性能监控显示"""
        # CPU使用率
        cpu_components = self.hardware_monitor.get_component_data("cpu")
        if cpu_components:
            for sensor in cpu_components[0].sensors:
                if sensor.name == "使用率":
                    self.cpu_usage_bar.setValue(int(sensor.value))
                    break
        
        # GPU使用率
        gpu_components = self.hardware_monitor.get_component_data("gpu")
        if gpu_components:
            for sensor in gpu_components[0].sensors:
                if sensor.name == "使用率":
                    self.gpu_usage_bar.setValue(int(sensor.value))
                    break
        
        # 内存使用率
        memory_components = self.hardware_monitor.get_component_data("memory")
        if memory_components:
            for sensor in memory_components[0].sensors:
                if sensor.name == "使用率":
                    self.memory_usage_bar.setValue(int(sensor.value))
                    break
    
    def add_transcode_task(self):
        """添加转码任务"""
        file_dialog = QFileDialog()
        file_paths, _ = file_dialog.getOpenFileNames(
            self, "选择视频文件", 
            self.config.get("paths.input_directory"),
            "视频文件 (*.mp4 *.avi *.mkv *.mov *.wmv *.flv *.ts *.m2ts)"
        )
        
        if file_paths:
            for file_path in file_paths:
                # 创建转码任务
                task = TranscodeTask(
                    task_id=f"task_{len(self.task_queue.get_all_tasks())}",
                    input_path=Path(file_path),
                    output_path=Path(file_path).with_suffix(".transcoded.mp4")
                )
                
                # 添加到队列
                asyncio.create_task(self.task_queue.add_task(task))
                
                # 开始执行任务
                asyncio.create_task(self.execute_task(task))
    
    async def execute_task(self, task: TranscodeTask):
        """执行转码任务"""
        # 这里需要集成实际的编码器
        # 暂时模拟任务执行
        import random
        
        task.start()
        
        for i in range(100):
            if task.status != TaskStatus.RUNNING:
                break
                
            progress = i + 1
            fps = random.uniform(20, 60)
            task.update_progress(progress, fps)
            
            await asyncio.sleep(0.1)  # 模拟处理时间
        
        if task.status == TaskStatus.RUNNING:
            task.complete()
    
    def start_all_tasks(self):
        """开始全部任务"""
        # 实现开始全部任务的逻辑
        pass
    
    def pause_all_tasks(self):
        """暂停全部任务"""
        # 实现暂停全部任务的逻辑
        pass
    
    def show_about_dialog(self):
        """显示关于对话框"""
        QMessageBox.about(self, "关于", 
            "视频转码系统 v0.1.0\n"
            "基于Python + PyQt6开发的高性能视频转码系统\n"
            "支持多GPU并行转码和实时监控\n\n"
            "作者: Homer Charles\n"
            "邮箱: homercharles@qq.com"
        )